﻿@using WishlistUtilities;
@{
	PageData["Title"] = "Edit List";

	WebSecurity.RequireAuthenticatedUser();

	var db = Database.Open("wishlistdb");
	var currentListID = UrlData[0];
	if (currentListID.IsEmpty()) {
		Response.Redirect("~/Shared/Errors/Error");
	}

	var currentList = db.QuerySingle("SELECT * FROM List WHERE Id=@0", currentListID);
    if (currentList.WishlistUserId != WebSecurity.CurrentUserId) {
        //User is attempting an unauthorized edit
		Response.Redirect("~/Shared/Errors/Error");
	}
}
<h1>Edit List</h1>
@{
    var errorMessage = "";
    
	if (IsPost) {
        //Edit List, ensuring that you don't update the name to a duplicate for that user
		if (!Request["listName"].IsEmpty() && !Request["listDescription"].IsEmpty()) {
			    var slug = SlugUtility.CreateSlug(Request["listName"]);
                //Replace slug character with SQL wildcard _
                var sqlSluggedListName = slug.Replace(SlugUtility.SLUGREPLACEMENTCHAR, '_');
                var duplicateList = (db.QueryValue("SELECT COUNT(*) FROM List WHERE Name LIKE @0 AND WishlistUserID = @1", 
                    sqlSluggedListName, WebSecurity.CurrentUserId) > 0) && (Request["listName"] != Request["originalListName"]);
			    if (!duplicateList) {
                    try {
                        db.Execute("UPDATE List SET Name=@0, Description=@1, Slug=@2 WHERE Id = @3",
                            Request["listName"], Request["listDescription"], slug, currentListID);
                    } catch (Exception) {
                        Response.Redirect("~/Shared/Errors/Error");
                    }
                	Response.Redirect("~/ManageLists");
			    } else {
    				errorMessage = "<li>You already have a list with this slug!</li>";
			    }
		} else {
    		errorMessage = "<li>List name or description cannot be empty.</li>";
		}
	}
    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}
<div>
    <fieldset>
        <form id="validateForm" method="post" action="">
            @RenderPage("~/Shared/_PrePopInputFormField.cshtml", 
                new { labelName = "listName", labelDisplay = "Name:", inputValue = currentList.Name, maxLength = 100, required = true})
	        @RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                new { labelName = "listDescription", labelDisplay = "Description:", inputValue = currentList.Description, maxLength = 500, required = true})
	        <input type="hidden" name="originalListName" value="@currentList.Name"/>
	        <div class="submit-group">
		        <input type="submit" value="Update" onclick="javascript:$('#validateForm').validate()" />
	        </div>
        </form>
    </fieldset>
</div>